/**
 * 本地树
 */
var LocalTree = function() {
	this.keys = [];
	this.data = {};
	this.openCallback = function() {};
	this.closeCallback = function() {};

	/**
	 * 添加数据
	 */
	this.addData = function($data, $pid) {
		if ($data.constructor === Array) {
			for (var i in $data) {
				this.addData($data[i], $pid);
			}
		} else {
			$data.id  = $data.id  ? $data.id  : IDGenerator.gen();
			$data.pid = $data.pid ? $data.pid : $pid;
			this.keys.push($data.id);
			this.data[$data.id] = $data;
			if ($data.children) {
				this.addData($data.children, $data.id);
				delete $data.children;
			}
		}
	}

	/**
	 * 在指定的容器生成
	 */
	this.renderTo = function($dom, $openCallback, $closeCallback) {
		if ($openCallback) {
			this.openCallback = $openCallback;
		}
		if ($closeCallback) {
			this.closeCallback = $closeCallback;
		}
		this._render($dom);
	}
	
	/*
	 * 在指定的容器生成
	 */
	this._render = function(dom) {
		var $this = this;
		var $dom  = $(dom);
		$dom.empty();
		$dom.append("<ul></ul>");

		for (var i in this.keys) {
			var key = this.keys[i];

			var $item = $("<span></span>");
			$item.attr("id", key);
			$item.addClass("treeItem");
			$item.addClass("close");
			$item.text(this.data[key].text);
			$item.click(function(){
				var $item = $(this);
				if ($item.hasClass("close")) {
					$item.removeClass("close");
					$item.addClass("open");
					// 回调openCallback
					$this.openCallback($this.data[$item.attr("id")]);
				} else {
					$item.removeClass("open");
					$item.addClass("close");
					// 回调closeCallback
					$this.closeCallback($this.data[$item.attr("id")]);
				}
			});
			var $node = $("<li></li>");
			$node.append($item);

			if (this.data[key].pid) {
				var $parentItem = $dom.find("#" + this.data[key].pid);
				if ($parentItem.next().length==0) {
					$parentItem.after("<ul></ul>");
				}
				$parentItem.next().append($node);
			} else {
				$dom.children("ul").append($node);
			}

		}
	}
}

